//
//  MCPickNumberViewController.m
//  TLYL
//
//  Created by miaocai on 2017/6/7.
//  Copyright © 2017年 TLYL01. All rights reserved.
//

#import "MCPickNumberViewController.h"
#import "MCLotteryHalllPickTableViewCell.h"
#import "MCLotteryHalllPickTableViewModel.h"
#import "UIImage+Extension.h"
#import "MCBallCollectionModel.h"
#import "MCPaySelectedLotteryTableViewController.h"
#import "MCPullMenuViewController.h"
#import "MCLotteryRecordView.h"
#import "MCRandomUntits.h"
#import "MCPaySelectedLotteryModel.h"
#import "MCPickNumberHeaderView.h"


@interface MCPickNumberViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    // 是否显示header视图，
    BOOL _isShowHeader;
}

#pragma mark -property

/**分组保存选中的号码球*/
@property (nonatomic,strong) NSMutableArray *selectedArrary;
/**开奖记录*/
@property (nonatomic,strong)MCLotteryRecordView * view_header;
/**随机数*/
@property (nonatomic,strong) NSMutableArray *randomBallArray;
/**cell强引用*/
@property (nonatomic,strong) NSMutableArray *cellArray;

@property (nonatomic,strong) MCPickNumberHeaderView * view_selectedCard;


@end

@implementation MCPickNumberViewController

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"天利娱乐";
    
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    /*
     * 初始化 小圆点
     */
    MCPaySLBaseModel * model=[MCPaySLBaseModel sharedMCPaySLBaseModel];
    if (model.dataSource.count>0) {
        self.addItemLabel.text = [NSString stringWithFormat:@"%d",(int)model.dataSource.count];
        self.addItemLabel.hidden = NO;
    }else{
        self.addItemLabel.hidden = YES;
    }
    
    
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    
}
- (void)dealloc{
    [self.cellArray removeAllObjects];
    NSLog(@"MCPickNumberViewController-----dealloc");
}
/*
 * 每次重置菜种
 */
-(void)MC_PICKNUMBERVC_INIT{
    typeof(self) weakSelf = self;
    //tableView滑到顶端
    if (weakSelf.baseTableView) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [weakSelf.baseTableView selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionTop];
    }
    //cellArray  add的方法始终在此方法后面
    if (weakSelf.cellArray.count==weakSelf.baseWFmodel.item.count) {
        [weakSelf clearAllButtonClick];
    }
    
    _view_selectedCard.dataSource=weakSelf.baseWFmodel;
}
-(void)pullLotteryRecordViewToTop{
    self.baseTableView.transform = CGAffineTransformIdentity;
    _isShowHeader=NO;
}

#pragma mark - setUpUI
- (void)setUpUI{
    self.view.backgroundColor = RGB(239, 239, 239);
    /**tabView 创建*/
    UITableView *tab = [[UITableView alloc] initWithFrame:CGRectMake(0, 114, G_SCREENWIDTH, G_SCREENHEIGHT) style:UITableViewStyleGrouped];
    [self.view addSubview:tab];
    tab.delegate = self;
    tab.dataSource = self;
    self.baseTableView = tab;
    self.baseTableView.backgroundColor=RGB(240, 240, 240);
    [self.view  insertSubview:self.view_header belowSubview:self.baseTableView];
    self.view_header.frame=CGRectMake(0, 130, G_SCREENWIDTH, MC_REALVALUE(300));
    self.baseTableView.estimatedRowHeight = MC_REALVALUE(90);
    self.baseTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
}



#pragma mark -UITableViewDataSource And UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if ([self.baseWFmodel.lineCount  isEqualToString: @""]) {
        return 0;
    } else {
        if ([self.baseWFmodel.filterCriteria isEqualToString:@"2"]) {
            return 1;
        } else {
            return [self.baseWFmodel.lineCount intValue];
        }
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *Identifier = [NSString stringWithFormat:@"MCLotteryHalllPickTableViewCell%ld%ld",(long)indexPath.section,(long)indexPath.row];
    
    MCLotteryHalllPickTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Identifier];
    
    if (cell == nil) {
        cell = [[MCLotteryHalllPickTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier];
    }
    if (![self.cellArray containsObject:cell]) {
        [self.cellArray addObject:cell];
    }
    
    cell.lotteriesType = self.lotteriesTypeModel.categoryID;
    
    if (![self.baseWFmodel.filterCriteria isEqualToString:@"2"]) {
        
        cell.dataSource = self.baseWFmodel.item[indexPath.row];
        
        cell.baseSlectedModel.index = (int)indexPath.row;
        
        __weak MCLotteryHalllPickTableViewCell *weakcell = cell;
        
        __weak typeof(self) weakSelf = self;
        cell.slectedBallBlock = ^(NSMutableArray *arr){
            weakcell.baseSlectedModel.selectedArray = arr;
            if (![weakSelf.selectedArrary containsObject:weakcell.baseSlectedModel] && arr.count != 0 ) {
                
                [weakSelf.selectedArrary addObject:weakcell.baseSlectedModel];
                
            }else if ([weakSelf.selectedArrary containsObject:weakcell.baseSlectedModel] && arr.count == 0){
                [weakSelf.selectedArrary removeObject:weakcell.baseSlectedModel];
            }
            weakSelf.baseWFmodel.baseSelectedModel = weakSelf.selectedArrary;
            
            if ([weakSelf.baseWFmodel.mutex isEqualToString:@"1"]) {
                
                [weakSelf dantuoWFMetuxWithCell:weakcell];
                
            }
            MCBallPropertyModel *model =  [MCStakeUntits GetBallPropertyWithWFModel:weakSelf.baseWFmodel];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"MCSTAKEUNITS_GETBALL_WF" object:nil userInfo:@{@"ballModel":model}];
        };
        
    }else{
        
    }
    cell.baseWFmodel = self.baseWFmodel;
    if (self.randomBallArray.count != 0) {
        cell.randomNumber = self.randomBallArray[indexPath.row];
    }
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return  self.baseWFmodel.lineH;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.view endEditing:YES];
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.00001;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if ([self.baseWFmodel.SelectedCardNumber intValue]!=0) {
        return (G_SCREENWIDTH-40*2-10*4)/5.0+20;
    }
    return 0.00001;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return  self.view_selectedCard;
}

#pragma mark -UIScrollViewDelegate
//减速动画开始前被调用
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    CGFloat offset = scrollView.contentOffset.y;
    
    if (_isShowHeader) {
        if (offset>MC_REALVALUE(20)) {
            [UIView animateWithDuration:0.4 animations:^{
                self.baseTableView.transform = CGAffineTransformIdentity;
            } completion:^(BOOL finished) {
                
                _isShowHeader=NO;
                
            }];
            
            
        }else{
            if (offset>0&&offset<MC_REALVALUE(20)) {
                self.baseTableView.transform = CGAffineTransformTranslate(self.baseTableView.transform, 0,-offset*1);
            }
        }
        if (self.baseTableView.frame.origin.y<MC_REALVALUE(300)) {
            [UIView animateWithDuration:0.4 animations:^{
                self.baseTableView.transform = CGAffineTransformIdentity;
            } completion:^(BOOL finished) {
                _isShowHeader=NO;
            }];
        }
    }
}


//结束拖动后被调用

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    if (decelerate){
        
        CGFloat offset = scrollView.contentOffset.y;
        if ((offset+MC_REALVALUE(50))<0&&_isShowHeader==NO) {
            [UIView animateWithDuration:0.4 animations:^{
                self.baseTableView.transform= CGAffineTransformTranslate(self.baseTableView.transform, 0,MC_REALVALUE(300));
            } completion:^(BOOL finished) {
                _isShowHeader = YES;
            }];
        }
    }
}
-(void)KaiJiangClick{
    if (!_isShowHeader) {
        [UIView animateWithDuration:0.4 animations:^{
            self.baseTableView.transform= CGAffineTransformTranslate(self.baseTableView.transform, 0,MC_REALVALUE(300));
        } completion:^(BOOL finished) {
            _isShowHeader = YES;
        }];
    }
    
}
#pragma mark -Custem Method
/**胆拖上下互斥玩法*/
- (void)dantuoWFMetuxWithCell:(MCLotteryHalllPickTableViewCell *)cell{
    
    if (self.selectedArrary.count >=2) {
        MCBaseSelectedModel *model1 = self.selectedArrary[0];
        MCBaseSelectedModel *model2 = self.selectedArrary [1];
        [model1.selectedArray enumerateObjectsUsingBlock:^(NSString * _Nonnull obj1, NSUInteger idx, BOOL * _Nonnull stop) {
            [model2.selectedArray enumerateObjectsUsingBlock:^(NSString * _Nonnull obj2, NSUInteger idx, BOOL * _Nonnull stop) {
                NSString *str1 = obj1;
                NSString *str2 = obj2;
                if ([self.baseWFmodel.tongxuan isEqualToString:@"2"]) {
                    str1 = [NSString stringWithFormat:@"0%@",[obj1 substringWithRange:NSMakeRange(0, 1)]];
                }
                if ([str1 isEqualToString:str2]) {
                    MCLotteryHalllPickTableViewCell *cell1 = [self.baseTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:model1.index inSection:0]];
                    MCLotteryHalllPickTableViewCell *cell2 = [self.baseTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:model2.index inSection:0]];
                    if (cell == cell2) {
                        for (MCBallCollectionModel*model in cell1.ballArray) {
                            if ([obj1 isEqualToString:model.textInfo]) {
                                model.seleted = NO;
                            }
                            [model1.selectedArray removeObject:obj1];
                        }
                        [cell1.ballColletionView reloadData];
                    } else {
                        for (MCBallCollectionModel*model in cell2.ballArray) {
                            if ([str1 isEqualToString:model.textInfo]) {
                                model.seleted = NO;
                            }
                            [model2.selectedArray removeObject:obj1];
                        }
                        [cell2.ballColletionView reloadData];
                    }
                }
            }];
        }];
    }
}

- (NSMutableArray *)setNumberSelectedArray{
    
    NSMutableArray *allNumberArray = [NSMutableArray array];
    
    for (NSInteger i = 0; i<self.baseWFmodel.item.count; i++) {
        NSMutableArray *sectionArray = [NSMutableArray array];
        MCLotteryHalllPickTableViewCell *cell = self.cellArray[i];
        for (MCBallCollectionModel *model in cell.ballArray) {
            if (model.seleted == YES) {
                [sectionArray addObject:model];
            }
        }
        if (sectionArray.count != 0) {
            [allNumberArray addObject:sectionArray];
        }
        
    }
    
    return  allNumberArray;
}
/**夫类方法*/
#pragma mark - 重写夫类方法
#pragma mark-机选
- (void)randomBtnClick{
    [super randomBtnClick];
    [self.baseWFmodel.baseSelectedModel removeAllObjects];
    NSMutableArray *arr = [MCRandomUntits Get_RandomArrWithModel:self.baseWFmodel];
    if (arr.count != self.cellArray.count) {return;}
    for (NSInteger i = 0; i<arr.count; i++) {
        MCLotteryHalllPickTableViewCell *cell = self.cellArray[i];
        for (MCBallCollectionModel *model in cell.ballArray) {
            model.seleted = NO;
        }
        NSMutableArray *randomNumber = arr[i];
        for (NSInteger j = 0; j<randomNumber.count; j++) {
            NSString *str = randomNumber[j];
            for (MCBallCollectionModel *model in cell.ballArray) {
                if ([str isEqualToString:model.textInfo]) {
                    model.seleted = YES;
                }
            }
        }
    }
    for (NSInteger i = 0; i<arr.count; i++) {
        MCLotteryHalllPickTableViewCell *cell = self.cellArray[i];
        [cell.ballColletionView reloadData];
    }
    
}
#pragma mark-清
- (void)clearAllButtonClick{
    
    self.baseWFmodel.stakeNumber=0;
    //单式清除操作
    if ([self.baseWFmodel.filterCriteria isEqualToString:@"2"]) {
        
        MCLotteryHalllPickTableViewCell *cell=[self.baseTableView  cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
        [cell danShiClear];
        self.baseWFmodel.danShiArray=nil;
        
    }else{
        for (NSInteger i = 0; i<self.baseWFmodel.item.count; i++) {
            
            MCLotteryHalllPickTableViewCell *cell = self.cellArray[i];
            for (MCBallCollectionModel *model in cell.ballArray) {
                model.seleted = NO;
            }
            [cell.ballColletionView reloadData];
            
        }
    }
}
#pragma mark-添加号码
- (void)addNumberToShoppingCar{
    //厘模式   >=0.02
    if ((ABS(self.baseWFmodel.yuanJiaoFen-0.001)<0.001)&&self.baseWFmodel.payMoney<0.02) {
        [MBProgressHUD showError:@"请至少选择0.02元！" toView:self.view];
        
    }else{
        //单式添加号码
        if ([self.baseWFmodel.filterCriteria isEqualToString:@"2"]) {
            
            //调用去错
            //如果没有问题   添加
            
            MCLotteryHalllPickTableViewCell *cell=[self.baseTableView  cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
            
            if ([cell danShiaddNumber]) {
                
                
                /*
                 * 加入数据
                 */
                MCPaySLBaseModel * model=[MCPaySLBaseModel sharedMCPaySLBaseModel];
                [model addDataSourceWithModel:self.baseWFmodel];
                self.addItemLabel.hidden=NO;
                self.addItemLabel.text = [NSString stringWithFormat:@"%d",(int)model.dataSource.count];
                
                [self clearAllButtonClick];
                
            }
            
        }else{
            
            if (self.baseWFmodel.stakeNumber>0) {
                
                /*
                 * 加入数据
                 */
                MCPaySLBaseModel * model=[MCPaySLBaseModel sharedMCPaySLBaseModel];
                [model addDataSourceWithModel:self.baseWFmodel];
                self.addItemLabel.hidden=NO;
                self.addItemLabel.text = [NSString stringWithFormat:@"%d",(int)model.dataSource.count];
                
                [self clearAllButtonClick];
                
                
            }else{
                [MBProgressHUD showError:@"请至少选择1注！" toView:self.view];
            }
            
        }
    }
    
    
    
}
#pragma mark-去投注
- (void)payTheSelectedNumbers{
    
    MCPaySLBaseModel * model=[MCPaySLBaseModel sharedMCPaySLBaseModel];
    //如果 当前角标为0  用户选择的球  够一注   也可以投注
    if (model.dataSource.count==0&&self.baseWFmodel.stakeNumber>0) {
        
        if (self.baseWFmodel.payMoney<0.02) {
            [MBProgressHUD showError:@"请至少选择0.02元！" toView:self.view];
            return;
        }
        [model addDataSourceWithModel:self.baseWFmodel];
        
        MCPaySelectedLotteryTableViewController *vc =  [[MCPaySelectedLotteryTableViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
        return;
        
    }
    
    if (self.baseWFmodel.stakeNumber<1&&model.dataSource.count<1) {
        [MBProgressHUD showError:@"请至少选择1注！" toView:self.view];
        return;
    }
    
    MCPaySelectedLotteryTableViewController *vc =  [[MCPaySelectedLotteryTableViewController alloc] init];
    
    [self.navigationController pushViewController:vc animated:YES];
    
    
}
#pragma mark - getter and setter
-(MCPickNumberHeaderView *)view_selectedCard{
    if (!_view_selectedCard) {
        _view_selectedCard=[[MCPickNumberHeaderView alloc]init];
        _view_selectedCard.dataSource=self.baseWFmodel;
    }
    return _view_selectedCard;
}

-(MCLotteryRecordView *)view_header{
    if (!_view_header) {
        _view_header=[[MCLotteryRecordView alloc]init];
    }
    return _view_header;
}

- (NSMutableArray *)cellArray{
    if (_cellArray== nil) {
        _cellArray = [NSMutableArray array];
    }
    return _cellArray;
}


- (NSMutableArray *)randomBallArray{
    if (_randomBallArray == nil) {
        _randomBallArray = [NSMutableArray array];
    }
    return _randomBallArray;
}

- (NSMutableArray *)selectedArrary{
    if (_selectedArrary == nil) {
        _selectedArrary = [NSMutableArray array];
    }
    return _selectedArrary;
}



- (void)setBaseWFmodel:(MCBasePWFModel *)baseWFmodel{
    
    [super setBaseWFmodel:baseWFmodel];
    baseWFmodel.lotteryCategories = self.lotteriesTypeModel.type;
    if ([baseWFmodel.filterCriteria isEqualToString:@"2"]) {
        self.baseTableView.frame = CGRectMake(0, 130, G_SCREENWIDTH, G_SCREENHEIGHT - 130);
    } else {
        self.baseTableView.frame = CGRectMake(0, 130, G_SCREENWIDTH, G_SCREENHEIGHT - 130- 49);
    }
    [self.cellArray removeAllObjects];
    [self.randomBallArray removeAllObjects];
    
    for (MCBaseSelectedModel *model in self.selectedArrary) {
        
        [model.selectedArray removeAllObjects];
    }
    [self.selectedArrary removeAllObjects];
    
    [self.baseTableView reloadData];
    
    
}


@end
